//
//  EventsListViewController.m
//  StanfordEvents
//
//  Created by Gongmyung on 6/30/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "EventsListViewController.h"


@implementation EventsListViewController

@synthesize eventsArray;
@synthesize managedObjectContext;
@synthesize addButton;
@synthesize locationManager;
@synthesize needsUpdate;


#pragma mark -
#pragma mark View lifecycle

- (id)initWithStyle:(UITableViewStyle)style withEvents:(NSMutableArray *)events {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
		//set the emoticon database
		eventsArray = events;
        [eventsArray retain];
	}
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Set the title.
    self.title = @"My Events";

    // Set up the buttons.
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
    
    addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addEvent)];
    addButton.enabled = NO;
    self.navigationItem.rightBarButtonItem = addButton;
    
    // Start the location manager.
    [[self locationManager] startUpdatingLocation];
    
    //set the events array
  //  [self setEventsArray:mutableFetchResults];
}


- (void)viewWillAppear:(BOOL)animated {
    if (needsUpdate == YES) {
        [eventsArray release];
        
        NSLog(@"Applying filters to EventsListViewController");
        
        NSError *error;
        NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
        [request setEntity:[NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]];
        [request setPredicate:[NSPredicate predicateWithFormat:@"(mine==1 || attended==1) && ANY tags.selected == 1"]];
        // describe how we want the data sorted
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"starttime" ascending:NO];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
        [request setSortDescriptors:sortDescriptors];
        NSMutableArray *results = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; 
        
        eventsArray = results;
        [eventsArray retain];
        
        [self.tableView reloadData];

        needsUpdate = NO;
    }
    
    [super viewWillAppear:animated];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)addEvent {
    /*
    PublishEventViewController *publishController = [[PublishEventViewController alloc]initWithNibName:@"PublishEventViewController" bundle:nil withContext:managedObjectContext];
    publishController.delegate = self;
    */
    
    PublishEventTableViewController *publishController = [[PublishEventTableViewController alloc] initWithStyle:UITableViewStyleGrouped withContext:managedObjectContext];
    publishController.delegate = self;
    
    [self.navigationController pushViewController:publishController animated:YES];
    [publishController release];
    
    // Create and configure a new instance of the Event entity
    
    /*
     CLLocation *location = [locationManager location];
     
     if (!location) {
     return;
     }
     
    Event *event = (Event *)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:managedObjectContext];
    
    CLLocationCoordinate2D coordinate = [location coordinate];

    [event setLatitude:[NSNumber numberWithDouble:coordinate.latitude]];
    [event setLongitude:[NSNumber numberWithDouble:coordinate.longitude]];
    [event setCreated:[NSDate date]];
    [event setTitle:@"Jiujitsu party"];
    
    NSError *error;
    if (![managedObjectContext save:&error]) {
        // wat
    }
 
    //insert the events in the table data source array
    [eventsArray insertObject:event atIndex:0];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
     */
}

- (void)PublishEventViewControllerDidFinish:(Event *)toPublish {
    //insert the event into the table data source array
    [eventsArray insertObject:toPublish atIndex:0];
    [self.tableView reloadData];
    //NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    //[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    //[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)addEventToList:(Event*)toAdd {
    if( ![eventsArray containsObject:toAdd] ) {
        [eventsArray insertObject:toAdd atIndex:0];
        [self.tableView reloadData];
        //NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        //[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (void)updateFilters {
    NSLog(@"Filters updated");
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [eventsArray count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // A date formatter for the time stamp
    static NSDateFormatter *dateFormatter = nil;
    if (dateFormatter == nil) {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
        [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    }
    
    static NSString *CellIdentifier = @"Cell";
    
    // Dequeue or create a new cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
    Event *event = (Event *)[eventsArray objectAtIndex:indexPath.row];
    
    cell.textLabel.text = [event title];
    cell.detailTextLabel.text = [dateFormatter stringFromDate:[event starttime]];
    
    if( [event.attended intValue] == 1 ) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *username, *password, *pid;
    
    NSUserDefaults *defaultSettings = [NSUserDefaults standardUserDefaults];
    username = [defaultSettings stringForKey:@"username"];
    password = [defaultSettings stringForKey:@"password"];
    pid = [defaultSettings stringForKey:@"pid"];
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        Event *event = (Event *)[eventsArray objectAtIndex:indexPath.row];
        
        if ( [event.pid intValue] != [pid intValue]) {
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Error Deleting Event"
                                  message:@"You are not the event creator"
                                  delegate:self
                                  cancelButtonTitle:@"Ok"
                                  otherButtonTitles: nil];
            [alert show];
            [alert autorelease];
        }
        else {
            //create a json object with the event properties
            NSMutableDictionary *eventDict = [[NSMutableDictionary alloc] init];
            [eventDict setObject:[event eid] forKey:@"eid"];
            //parse object into json
            SBJSON *parser = [[SBJSON alloc] init];
            NSString *jsonEvent = [parser stringWithObject:eventDict];
        
            NSURL *url = [NSURL URLWithString:@"http://colby.stanford.edu/community_vibe/concierge/rpc.php"];
            ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
        
            [request setPostValue:username forKey:@"name"];
            [request setPostValue:password forKey:@"key"];
            [request setPostValue:@"postMessage" forKey:@"do"];
            [request setPostValue:jsonEvent forKey:@"content"];
            [request setPostValue:@"stanford_events,delete" forKey:@"tags"];
            [request startSynchronous];
            
            event = nil;
            [eventsArray removeObjectAtIndex:indexPath.row];
            [self.tableView reloadData];
        }
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	
    EventDetailTableViewController *detailViewController = [[EventDetailTableViewController alloc] initWithStyle:UITableViewStyleGrouped withEvent:[eventsArray objectAtIndex:indexPath.row] ];
    detailViewController.delegate = self;
    // ...
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}

//delegate method for EventDetailTableViewController 
- (void) didCheckIn {
    [self.tableView reloadData];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}


/*
 * Accessor method that dynamically creates a core location manager
 */
- (CLLocationManager *)locationManager {
    if (locationManager != nil) {
        return locationManager;
    }
    
    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    locationManager.delegate = self;
    
    return locationManager;
}

/*
 * Core Location Manager Delegate Methods
 */
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    addButton.enabled = YES;
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    addButton.enabled = NO;
}


//publish event view controller delegate methods
- (UINavigationController *)navController {
    return self.navigationController;
}

- (void)viewDidUnload {
    self.eventsArray = nil;
    self.locationManager = nil;    
    self.addButton = nil;
}

- (void)dealloc {
    [managedObjectContext release];
    [eventsArray release];
    [locationManager release];
    [addButton release];
    [super dealloc];
}


@end

